/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View.components;

import Model.Producto;
import Presenter.ProductoPresenter;
import Principals.Validadores;
import View.ventas.Frm_RegistrarPedido;
import java.awt.Dimension;
import java.awt.Point;
import java.util.List;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author walter
 */
public class PopUpBuscarProducto extends javax.swing.JDialog {

    private JDesktopPane pnl;
    private List<Producto> lstProducto;
    private Producto producto;
    private String errorMsg;
    private DefaultTableModel mdlBuscarProducto;
    private Validadores val = new Validadores();

    /**
     * Creates new form Frm_BuscarProducto
     */
    public PopUpBuscarProducto() {
        initComponents();
        val.desactivarAccionPegar(txtNombre);
    }

    public PopUpBuscarProducto(JFrame parent) {
        super(parent, true);
        if (parent != null) {
            Dimension parentSize = parent.getSize();
            Point p = parent.getLocation();
            setLocation(p.x + parentSize.width / 4, p.y + parentSize.height / 4);
        }
        initComponents();
        tblBuscarProducto.getTableHeader().setReorderingAllowed(false);
        mdlBuscarProducto = new DefaultTableModel();
        this.pack();
        this.setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
        pnl = new JDesktopPane() ;
        pnlBuscarProducto = new javax.swing.JPanel();
        lblNombre = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        btnBuscar = new javax.swing.JToggleButton();
        pnlResultadosProducto = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblBuscarProducto = new javax.swing.JTable();
        jToolBar1 = new javax.swing.JToolBar();
        btnToolNuevo = new javax.swing.JButton();
        btnToolModificar = new javax.swing.JButton();
        btnToolGuardar = new javax.swing.JButton();
        btnToolEliminar = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JToolBar.Separator();
        btnToolLimpiar = new javax.swing.JButton();
        btnToolBuscar = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        btnToolCancelar = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();

        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        pnlBuscarProducto.setBorder(javax.swing.BorderFactory.createTitledBorder("Búsqueda"));

        lblNombre.setText("Nombre:");

        txtNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNombreKeyTyped(evt);
            }
        });

        btnBuscar.setText("Buscar");
        btnBuscar.setAutoscrolls(true);
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlBuscarProductoLayout = new javax.swing.GroupLayout(pnlBuscarProducto);
        pnlBuscarProducto.setLayout(pnlBuscarProductoLayout);
        pnlBuscarProductoLayout.setHorizontalGroup(
            pnlBuscarProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlBuscarProductoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblNombre)
                .addGap(18, 18, 18)
                .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnBuscar)
                .addContainerGap())
        );
        pnlBuscarProductoLayout.setVerticalGroup(
            pnlBuscarProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlBuscarProductoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlBuscarProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNombre)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnBuscar))
                .addContainerGap(16, Short.MAX_VALUE))
        );

        pnlResultadosProducto.setBorder(javax.swing.BorderFactory.createTitledBorder("Resultados"));

        tblBuscarProducto.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id Producto", "Nombre", "Precio Costo (S/.)", "Precio Lista (S/.)", "Stock","Estado"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false , false
            };
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblBuscarProducto.addMouseListener( new java.awt.event.MouseAdapter(){
            @Override
            public void mouseClicked( java.awt.event.MouseEvent evt ){
                tblBuscarProductoMouseClicked( evt ) ;
            }
        });
        jScrollPane1.setViewportView(tblBuscarProducto);

        javax.swing.GroupLayout pnlResultadosProductoLayout = new javax.swing.GroupLayout(pnlResultadosProducto);
        pnlResultadosProducto.setLayout(pnlResultadosProductoLayout);
        pnlResultadosProductoLayout.setHorizontalGroup(
            pnlResultadosProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 478, Short.MAX_VALUE)
        );
        pnlResultadosProductoLayout.setVerticalGroup(
            pnlResultadosProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE)
        );

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setBorderPainted(false);

        btnToolNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Nuevo.png"))); // NOI18N
        btnToolNuevo.setFocusable(false);
        btnToolNuevo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolNuevo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolNuevoActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolNuevo);

        btnToolModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Editar.png"))); // NOI18N
        btnToolModificar.setFocusable(false);
        btnToolModificar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolModificar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolModificarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolModificar);

        btnToolGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Guardar.png"))); // NOI18N
        btnToolGuardar.setEnabled(false);
        btnToolGuardar.setFocusable(false);
        btnToolGuardar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolGuardar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(btnToolGuardar);

        btnToolEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Eliminar.png"))); // NOI18N
        btnToolEliminar.setEnabled(false);
        btnToolEliminar.setFocusable(false);
        btnToolEliminar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolEliminar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolEliminarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolEliminar);
        jToolBar1.add(jSeparator3);

        btnToolLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Limpiar.png"))); // NOI18N
        btnToolLimpiar.setFocusable(false);
        btnToolLimpiar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolLimpiar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolLimpiarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolLimpiar);

        btnToolBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Buscar.png"))); // NOI18N
        btnToolBuscar.setFocusable(false);
        btnToolBuscar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolBuscar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolBuscarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolBuscar);
        jToolBar1.add(jSeparator2);

        btnToolCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Cancelar.png"))); // NOI18N
        btnToolCancelar.setFocusable(false);
        btnToolCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolCancelar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolCancelarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolCancelar);
        jToolBar1.add(jSeparator1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(pnl);
        pnl.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlBuscarProducto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(pnlResultadosProducto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jToolBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(pnlBuscarProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlResultadosProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        this.add( pnl ) ;
    }// </editor-fold>       
    
    private void btnToolNuevoActionPerformed(java.awt.event.ActionEvent evt) {
        this.setVisible(false);
        new PopUpNuevoProducto((Index) this.getParent());
    }

    private void btnToolModificarActionPerformed(java.awt.event.ActionEvent evt) {
    }

    private void btnToolLimpiarActionPerformed(java.awt.event.ActionEvent evt) {
        limpiar();
    }

    private void btnToolBuscarActionPerformed(java.awt.event.ActionEvent evt) {
    }

    private void btnToolCancelarActionPerformed(java.awt.event.ActionEvent evt) {
        this.setVisible(false);
    }

    private void btnToolEliminarActionPerformed(java.awt.event.ActionEvent evt) {
    }

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {                                          
        try{
        String nombre = txtNombre.getText() ;
        lstProducto = ProductoPresenter.buscarProducto(nombre);
        
        mdlBuscarProducto.setNumRows( 0 ) ;
        mdlBuscarProducto = (DefaultTableModel)tblBuscarProducto.getModel() ;

        for(int i = 0 ; i < lstProducto.size() ; i++){
            Producto p = lstProducto.get( i ) ;
                 
                String estado="";
                switch (p.getEstado()){
                    case 0: estado="Inactivo"; break;
                    case 1: estado="Activo"; break;
                }  
            Object[] row = new Object[]{ p.getIdProducto(), p.getNombre(),p.getPrecioCosto(),p.getPrecioLista(),p.getStock(),estado } ;
            mdlBuscarProducto.insertRow( i , row ) ;
        }
        tblBuscarProducto.setVisible( true ) ;

        JOptionPane.showMessageDialog(this, "Se encontraron "+ mdlBuscarProducto.getRowCount()+ " coincidencias");
        }
        catch (Exception e){
            JOptionPane.showMessageDialog(this, "No se pudo realizar la transacción.");
            System.out.println("MENSAJE DE ERROR:"+e);
        }        
    }                                         

    private void txtNombreKeyTyped(java.awt.event.KeyEvent evt) {                                   
        val.validaCaracteresRaros(evt);
        val.validaMaxSize(evt, 20, txtNombre.getText());
        txtNombre.setTransferHandler(null);
    }

    private void tblBuscarProductoMouseClicked(java.awt.event.MouseEvent evt) {
        if (evt.getClickCount() == 2){
            if (this.tblBuscarProducto.getSelectedRow() == -1) {
                errorMsg = "Por favor seleccione un producto.";
                JOptionPane.showMessageDialog(this, errorMsg);
            } else {
                int i = this.tblBuscarProducto.getSelectedRow();
                producto = this.lstProducto.get(i);

                if(producto.getEstado()==0){
                    errorMsg = "Por favor seleccione un producto activo.";
                    JOptionPane.showMessageDialog(this, errorMsg);
                }
                else{
                    Index p = (Index) (this.getParent());
                    if ((p.getContainer().getClass().toString().equals("class View.ventas.Frm_RegistrarPedido"))) {
                        try {
                            this.setVisible(false);
                            Frm_RegistrarPedido owner = (Frm_RegistrarPedido) p.getContainer();
                            owner.actualizarDatosProducto(producto);
                        } catch (Exception e) {
                        }
                    }
                }
            }
        }
    }

    private void limpiar() {
        txtNombre.setText("");
        mdlBuscarProducto.setNumRows(0);
        mdlBuscarProducto = (DefaultTableModel) tblBuscarProducto.getModel();
    }
    // Variables declaration - do not modify                     
    private javax.swing.JToggleButton btnBuscar;
    private javax.swing.JButton btnToolBuscar;
    private javax.swing.JButton btnToolCancelar;
    private javax.swing.JButton btnToolEliminar;
    private javax.swing.JButton btnToolGuardar;
    private javax.swing.JButton btnToolLimpiar;
    private javax.swing.JButton btnToolModificar;
    private javax.swing.JButton btnToolNuevo;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar.Separator jSeparator3;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel lblNombre;
    private javax.swing.JPanel pnlBuscarProducto;
    private javax.swing.JPanel pnlResultadosProducto;
    private javax.swing.JTable tblBuscarProducto;
    private javax.swing.JTextField txtNombre;
    // End of variables declaration                    
}
